package cn.calm.tomcat.clound.doundry.datasource;

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.Name;
import javax.naming.Reference;
import javax.naming.spi.ObjectFactory;

import org.cloudfoundry.runtime.env.CloudEnvironment;
import org.cloudfoundry.runtime.env.MysqlServiceInfo;
import org.cloudfoundry.runtime.env.RdbmsServiceInfo;
import org.cloudfoundry.runtime.service.AbstractDataSourceCreator;
import org.cloudfoundry.runtime.service.relational.MysqlServiceCreator;

public class CloundFoundryDataSource  implements ObjectFactory {

	public Object getObjectInstance(Object obj, Name name, Context nameCtx,
			Hashtable<?, ?> environment) throws Exception {
		if ((obj == null) || !(obj instanceof Reference)) {
            return null;
        }
        Reference ref = (Reference) obj;
        System.out.println(ref);
		CloudEnvironment env = new CloudEnvironment();
		System.out.println(ref.get("serviceName").getContent().toString());
		RdbmsServiceInfo info = env.getServiceInfo(ref.get("serviceName").getContent().toString(), RdbmsServiceInfo.class);
		
		AbstractDataSourceCreator<MysqlServiceInfo> creator=new MysqlServiceCreator();
		return creator.createService(info);
	}
}
